<template>
  <el-dialog :title="title" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
    <el-form ref="roleForm" label-width="160px" :model="formData" :rules="rules">
      <el-form-item label="分类名称" prop="catename">
        <el-input v-model="formData.catename" style="width:520px" placeholder="请输入分类名" />
      </el-form-item>
      <el-form-item label="图标class" prop="icon">
        <el-input v-model="formData.icon" style="width:200px" placeholder="请输入class名" />
        <el-link href="https://fontawesome.com.cn/v4/icons-ui/">
          具体参见fontawesome图标库
        </el-link>
      </el-form-item>
      <el-form-item label="排序大小">
        <el-input-number v-model="formData.sort_num" style="width:200px" :min="1" />
      </el-form-item>
      <el-row type="flex" justify="center">
        <el-button type="primary" size="small" @click="addArticleCate">确定</el-button>
        <el-button size="small" @click="closeDialog">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { addArticleCateApi, getArticleDetailApi, editArticleCateApi } from '@/api/contnet/cate'
export default {
  data() {
    return {
      // 控制弹框显示隐藏
      showDialog: false,
      // 表单参数
      formData: {
        catename: '',
        icon: '',
        sort_num: 1
      },
      // 表单校验规则
      rules: {
        catename: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑分类' : '新增分类'
    }
  },
  methods: {
    // 关闭dialog
    closeDialog() {
      this.showDialog = false
      // 重置表单校验
      this.$refs.roleForm.resetFields()
      // 清空表单
      this.formData = {
        catename: '',
        icon: '',
        sort_num: 1
      }
    },
    // 添加分类
    async addArticleCate() {
      try {
        await this.$refs.roleForm.validate()
      } catch (error) {
        return console.log(error)
      }
      if (this.formData.id) {
        // 修改逻辑
        await editArticleCateApi(this.formData)
        this.$message.success('修改成功')
      } else {
        // 添加逻辑
        await addArticleCateApi(this.formData)
        this.$message.success('添加成功')
      }
      // 清空表单及校验
      this.closeDialog()
      // 更新数据
      this.$emit('updata')
    },
    // 编辑内容回显
    async getArticleDetail(id) {
      this.showDialog = true
      const res = await getArticleDetailApi(id)
      this.formData = res.data
    }
  }
}
</script>
<style lang="scss" scoped>
.el-link {
  margin-left: 20px;
}
</style>
